<script setup>
import {ref, computed} from 'vue'
import {useUserInfoStore} from "@/stores/userInfo.js";
import {updateUserPasswordService} from "@/api/user.js";
import {ElMessage} from 'element-plus'
import { useRouter } from 'vue-router'
import CryptoJS from 'crypto-js';

// 获取用户信息
const userInfoStore = useUserInfoStore()
const userInfo = ref({...userInfoStore.userInfo})
//获取路由
const router = useRouter()

const MyuserInfo = ref({
  originalPassword: '',
  password: '',
  repassword: ''
})

function validatePass(rule, value, callback){
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value !== MyuserInfo.value.password) {
    callback(new Error("请确保两次输入密码一致!"))
  } else {
    callback()
  }
}

const rules = {
  originalPassword: [
    { required: true, message: '请输入原始密码', trigger: 'blur' },
    { min: 5, max: 16, message: '请输入5~16位非空字符', trigger: 'blur' }
  ],
  password:[
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 16, message: '请输入5~16位非空字符', trigger: 'blur' }
  ],
  repassword:[
    { validator: validatePass, trigger: 'blur' }
  ]
}



// 更新密码
async function updateUserInfo() {
  let res = await updateUserPasswordService(
      MyuserInfo.value.originalPassword,
      MyuserInfo.value.password,
      MyuserInfo.value.repassword)
  let message = res.data

  if(message === null){
    ElMessage.success("密码修改成功，请重新登录")
    router.push('/login')
  }else{
    ElMessage.error(message)
  }

}

</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>修改密码</span>
      </div>
    </template>
    <el-row>
      <el-col :span="12">
        <el-form :model="MyuserInfo" :rules="rules" label-width="100px" size="large">
          <el-form-item label="原始密码" prop="originalPassword">
            <el-input v-model="MyuserInfo.originalPassword"></el-input>
          </el-form-item>

          <el-form-item label="新密码" prop="password">
            <el-input v-model="MyuserInfo.password" type="password"></el-input>
          </el-form-item>

          <el-form-item label="确认密码" prop="repassword">
            <el-input v-model="MyuserInfo.repassword" type="password"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="updateUserInfo">提交修改</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
</template>

